//
//  CommentViewController.m
//  RedManStock
//
//  Created by lanou3g on 15/7/21.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "CommentViewController.h"
#import "CommentTableViewCell.h"
#import "MyHandle.h"
#import "HotPost.h"
#import "AFNetworking.h"
#import "Comment.h"
#import "MBProgressHUD.h"
@interface CommentViewController ()
//声明一个数据源属性
@property(nonatomic,retain)NSMutableArray *commentArray;
@property(nonatomic,retain)NSMutableArray *hotPostArray;
//@property(nonatomic,retain)Comment *comment;
@end

@implementation CommentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //因为content内容要变，所以用copy属性的newHotPost复制传过来的hotPost,指向两块不同的堆区内存
    
    
    
    
    self.SedHotPost=self.hotPost;
    self.update=YES;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"CommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"commentCell"];
    
//        UIImage *image = [UIImage imageNamed:@"1431608058217.png"];
//        UIImageView *imageView = [[UIImageView alloc]initWithImage:image];
//        imageView.frame = CGRectMake(0, 0, 320, 200);
//    
// self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, imageView.frame.size.height)];
//    
//    [self.tableView.tableHeaderView addSubview:imageView];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    if (self.update) {
        [self loadNewData];
    }
    self.update=NO;
}






//下拉刷新方法：拼接网址
#pragma mark- 下拉刷新 -
-(void)loadNewData{
    
    //    出现大菊花
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    //给字符串
    NSString *urlStr = @"http://api.gongniucaijing.com/Weiba/listcomment";

    
    //下拉刷新，第一步就要remove数据源
    [self.commentArray removeAllObjects];
    
    //请求网络
    [[MyHandle new] requestDataWithURLStr:urlStr parameterBlock:^NSDictionary *{
        NSDictionary *dic=@{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                            @"number":@"15",
                            @"post_id":self.SedHotPost.post_idSB};
        return dic;
        
    } successBlock:^(NSDictionary *responseDic) {
        
        [self dataSourceWithJasonDic:responseDic];
        //结束Header
        [self.tableView.header endRefreshing];
        
    } errorBlock:^(NSError *error) {
    
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        [self.tableView.header endRefreshing];

        
    }];
    
    

    
}



//上拉加载更多方法：拼接网址，参数的改变
#pragma mark- 上拉加载方法 -
-(void)loadMoreData{
    
    //给字符串
    NSString *urlStr = @"http://api.gongniucaijing.com/Weiba/listcomment";
    
    //无需清空数据源
    
    //请求网络+给数据源赋值
    [[MyHandle new] requestDataWithURLStr:urlStr parameterBlock:^NSDictionary *{
        NSDictionary *dic=@{@"token":@"d58f02522dac7e698a4600c8b18ff02c0b9fa6df",
                            @"number":@"15",
                            @"post_id":self.SedHotPost.post_idSB,
                            @"offset":[NSString stringWithFormat:@"%lu",(unsigned long)self.commentArray.count]};
        return dic;
        
    } successBlock:^(NSDictionary *responseDic) {
        
        [self dataSourceWithJasonDic:responseDic];
//        结束footer
        [self.tableView.footer endRefreshing];
        
    } errorBlock:^(NSError *error) {
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接错误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [alertView show];
        [self.tableView.footer endRefreshing];

        
    }];
    
}



//上两个方法执行一半，后一半通过该公有方法执行: 请求网络，数据源赋值，reloadData，[self.tableView headerEndRefreshing]
#pragma mark- 请求网络，数据源赋值，reloadData，[self.tableView headerEndRefreshing] -
- (void)dataSourceWithJasonDic:(NSDictionary *)dic{
//---------------------------headview---------------------------
    if (dic) {
        NSDictionary* dic2 = [dic objectForKey:@"data"];
        NSDictionary* dic3 = [dic2 objectForKey:@"post"];
        HotPost *hotPost = [[HotPost alloc]init];
        [hotPost setValuesForKeysWithDictionary:dic3];
        
        UIImageView *post_avatarImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 16, 40, 40)];
        post_avatarImageView.layer.cornerRadius = 20;
        post_avatarImageView.layer.masksToBounds = YES;
        [post_avatarImageView sd_setImageWithURL:[NSURL URLWithString:hotPost.post_avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            
        }];
        post_avatarImageView.backgroundColor = [UIColor redColor];
        
        UILabel *post_nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(55, 26, 128, 20)];
        post_nameLabel.text = hotPost.post_name;
        post_nameLabel.font = [UIFont systemFontOfSize:12];
        post_nameLabel.textColor = [UIColor colorWithRed:0.149 green:0.467 blue:0.949 alpha:1.000];
        
        UILabel *post_timeLabel= [[UILabel alloc]initWithFrame:CGRectMake(236, 26, 74, 20)];

        post_timeLabel.text = hotPost.post_timeSB;
        post_timeLabel.font = [UIFont systemFontOfSize:12];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 64, 300, 17)];
        NSString * titleStr = [hotPost.title stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
        titleLabel.font = [UIFont systemFontOfSize:14];
        titleLabel.text = titleStr;
        [MyHandle new];
        CGFloat contentLabelHeight = [MyHandle stringHeight:hotPost.contentSB fontSize:12 width:self.tableView.bounds.size.width-20];
        
        UILabel *contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 89, self.view.bounds.size.width-20, contentLabelHeight)];
        contentLabel.font = [UIFont systemFontOfSize:12];
        
        NSString * contentStr = [hotPost.contentSB stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
        NSString * content = [contentStr stringByReplacingOccurrencesOfString:@"<br/>" withString:@"\n"];
        contentLabel.numberOfLines = 0;
        contentLabel.text = content;
        
        UIImage *post_logoImage = self.SedHotPost.post_logoImage;
        
        if (self.SedHotPost.post_logoImage) {
            
            CGFloat post_avatarImageViewHeight = ((self.view.bounds.size.width-20)*post_logoImage.size.height)/post_logoImage.size.width;

            
            UIImageView *post_logoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(contentLabel.frame), self.view.bounds.size.width-20, post_avatarImageViewHeight)];
            post_logoImageView.image = post_logoImage;
            
            
            
            CGFloat headViewHeight = 40+20+20+17+contentLabelHeight+post_avatarImageViewHeight;
            
            self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, headViewHeight)];
            
            [self.tableView.tableHeaderView addSubview:post_avatarImageView];
            [self.tableView.tableHeaderView addSubview:post_nameLabel];
            [self.tableView.tableHeaderView addSubview:post_timeLabel];
            [self.tableView.tableHeaderView addSubview:titleLabel];
            [self.tableView.tableHeaderView addSubview:contentLabel];
            [self.tableView.tableHeaderView addSubview:post_logoImageView];
            
        }else{

            
            UIImageView *post_logoImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(contentLabel.frame), 0, 0)];
            post_logoImageView.image = post_logoImage;
            
            
            
            CGFloat headViewHeight = 40+20+20+17+contentLabelHeight;
            
            self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, headViewHeight)];
            
            [self.tableView.tableHeaderView addSubview:post_avatarImageView];
            [self.tableView.tableHeaderView addSubview:post_nameLabel];
            [self.tableView.tableHeaderView addSubview:post_timeLabel];
            [self.tableView.tableHeaderView addSubview:titleLabel];
            [self.tableView.tableHeaderView addSubview:contentLabel];
            [self.tableView.tableHeaderView addSubview:post_logoImageView];
            
        }

        
        
        
        
        
    }
    
//---------------------------------------------------------
    
    
    if (dic) {
        
        NSDictionary* dic2 = [dic objectForKey:@"data"];
        NSDictionary* dic3 = [dic2 objectForKey:@"post"];
        self.SedHotPost.contentSB=[dic3 objectForKey:@"content"];
        
        NSArray *commentListArray=[dic2 objectForKey:@"lists"];
        for (NSDictionary *commentListsDic in commentListArray) {
            
            Comment *comment=[[Comment alloc]init];
            [comment setValuesForKeysWithDictionary:commentListsDic];
            
            NSDictionary *dic4=[commentListsDic objectForKey:@"comment_reply"];
            NSArray *array4=[dic4 objectForKey:@"lists"];
            
            for (NSDictionary *replyDic in array4) {
                Reply *reply=[[Reply alloc]init];
                [reply setValuesForKeysWithDictionary:replyDic];
                [comment.replyArray addObject:reply];
            }
            [self.commentArray addObject:comment];
        }
        
        //        结束大菊花
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        //刷新视图
        [self.tableView reloadData];
        
    }
    else{
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请求失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];

        
    }
    
    
}




#pragma mark- 重写数据源get方法 -
//重写get方法，防止用点语法之前忘记给数据源分配内存
-(NSMutableArray *)commentArray{
    if (_commentArray == nil) {
        _commentArray = [NSMutableArray array];
    }
    return _commentArray;
}




#pragma mark- 协议方法：分行 -
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [self.commentArray count];
}


#pragma mark- 分区 -
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}


#pragma mark- 协议方法cell复用 -
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
    
    Comment *comment = [self.commentArray objectAtIndex:indexPath.row];
    
    cell.comment = comment;
    cell.comment_nameLabel.textColor = [UIColor colorWithRed:0.153 green:0.478 blue:0.949 alpha:1.000];
    if (comment.comment_avatarImage == nil) {
        
        [cell.comment_avatarImageView sd_setImageWithURL:[NSURL URLWithString:comment.comment_avatar] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            
            comment.comment_avatarImage=image;
           
        }];
        
    }
    cell.comment_avatarImageView.image=comment.comment_avatarImage;
    
    
    
    return cell;
    
}

#pragma mark- cell高度自适应 -
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    [MyHandle new];
    CGFloat height2 = 0;
    Comment *comment = self.commentArray[indexPath.row];
    CGFloat height1 = [MyHandle stringHeight:comment.content fontSize:12 width:250];
    for (int i = 0; i<comment.replyArray.count; i++) {

        Reply *reply=(Reply *)comment.replyArray[i];
        NSString *replyLabelText =[NSString stringWithFormat:@"%@: %@",reply.reply_name,reply.comment];
        height2 = height2+[MyHandle stringHeight:replyLabelText fontSize:12 width:250];
        
    }
    
    
    CGFloat h = 15+40+15+15+18+15;
    
    if (comment.replyArray.count==0) {
        return height1+h;
    }
    else if(comment.replyArray.count==1){
        return height1+height2+h+15;
    }
    else{
        return height1+height2+h+25;
    }
}











- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
